/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package group;

import static artist.ListArtistForm.ArtistTable;
import static artist.ListArtistForm.artistList;
import java.util.Iterator;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import radiostation_POJOS.*;

/**
 *
 * @author elpida
 */
public class ListMusicGroupForm extends javax.swing.JFrame {
    int selectedRow;
    private static EntityManager em;
    Musicgroup group;

    /**
     * Creates new form ListMusicGroupForm
     */
    public ListMusicGroupForm() {
        initComponents();
        setLocationRelativeTo(null);        
        checkButtons();
        em =javax.persistence.Persistence.createEntityManagerFactory("RadiostationPU").createEntityManager();
           
        
    }
    
    public void checkButtons(){
        selectedRow = GroupTable.getSelectedRow();
        delGroup.setEnabled(selectedRow >= 0);
        editGroup.setEnabled(selectedRow >= 0);

        if (selectedRow >= 0) {
            group = musicgroupList.get(GroupTable.convertRowIndexToModel(selectedRow));
        }
    
    }
    

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        RadiostationPUEntityManager = java.beans.Beans.isDesignTime() ? null : javax.persistence.Persistence.createEntityManagerFactory("RadiostationPU").createEntityManager();
        musicgroupQuery = java.beans.Beans.isDesignTime() ? null : RadiostationPUEntityManager.createQuery("SELECT m FROM Musicgroup m");
        musicgroupList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : org.jdesktop.observablecollections.ObservableCollections.observableList(musicgroupQuery.getResultList());
        jLabel1 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        GroupTable = new javax.swing.JTable();
        jButton1 = new javax.swing.JButton();
        editGroup = new javax.swing.JButton();
        delGroup = new javax.swing.JButton();
        jButton4 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Διαχείριση Μουσικών Συγκροτημάτων");

        jLabel1.setFont(new java.awt.Font("Monotype Corsiva", 1, 18)); // NOI18N
        jLabel1.setForeground(new java.awt.Color(153, 0, 51));
        jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel1.setText("Μουσικά    Συγκροτήματα");

        GroupTable.setFont(new java.awt.Font("Calibri", 0, 12)); // NOI18N

        org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, musicgroupList, GroupTable);
        org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${name}"));
        columnBinding.setColumnName("Ονομασία");
        columnBinding.setColumnClass(String.class);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${formationdate}"));
        columnBinding.setColumnName("Ημερομηνία Ίδρυσης");
        columnBinding.setColumnClass(java.util.Date.class);
        bindingGroup.addBinding(jTableBinding);
        jTableBinding.bind();
        GroupTable.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                GroupTableMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(GroupTable);

        jButton1.setFont(new java.awt.Font("Calibri", 1, 12)); // NOI18N
        jButton1.setForeground(new java.awt.Color(153, 0, 51));
        jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/Add.png"))); // NOI18N
        jButton1.setText("Δημιουργία");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        editGroup.setFont(new java.awt.Font("Calibri", 1, 12)); // NOI18N
        editGroup.setForeground(new java.awt.Color(153, 0, 51));
        editGroup.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/Edit.png"))); // NOI18N
        editGroup.setText("Τροποποίηση");
        editGroup.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                editGroupActionPerformed(evt);
            }
        });

        delGroup.setFont(new java.awt.Font("Calibri", 1, 12)); // NOI18N
        delGroup.setForeground(new java.awt.Color(153, 0, 51));
        delGroup.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/Delete.png"))); // NOI18N
        delGroup.setText("Διαγραφή");
        delGroup.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                delGroupActionPerformed(evt);
            }
        });

        jButton4.setFont(new java.awt.Font("Calibri", 1, 12)); // NOI18N
        jButton4.setForeground(new java.awt.Color(153, 0, 51));
        jButton4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/Log Out.png"))); // NOI18N
        jButton4.setText("Έξοδος");
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(38, 38, 38)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(editGroup)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(delGroup, javax.swing.GroupLayout.PREFERRED_SIZE, 118, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 104, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 477, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(74, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(0, 0, Short.MAX_VALUE)
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 321, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(171, 171, 171))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 269, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 21, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(editGroup)
                    .addComponent(delGroup)
                    .addComponent(jButton4))
                .addContainerGap())
        );

        bindingGroup.bind();

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
        // TODO add your handling code here:
         dispose();
    }//GEN-LAST:event_jButton4ActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        // TODO add your handling code here:
       new NewOrModifyGroupFrom(null).setVisible(true);
       this.dispose();
            
    }//GEN-LAST:event_jButton1ActionPerformed

    private void editGroupActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_editGroupActionPerformed
        // TODO add your handling code here:
        int s=GroupTable.getSelectedRow();
        if (s>=0){//αν επέλεξα κάτι από τα καλλιτέχνη
            Musicgroup m = musicgroupList.get(s);
            NewOrModifyGroupFrom em = new NewOrModifyGroupFrom(m);
            em.setVisible(true);
            dispose();
        }
        else{
            JOptionPane.showMessageDialog(null, "Δεν επιλέξατε κάποιο καλλιτέχνη", "Λάθος", JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_editGroupActionPerformed

    private void delGroupActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_delGroupActionPerformed
//διαγραφή γκρουπ από βάση, σβήνω πρώτα τα αλμπουμ με loop και μετά το γκρουπ, δεν έπαιζε το cascade
        int s=GroupTable.getSelectedRow();
        if (s>=0){           
            Musicgroup m = musicgroupList.get(s);
            if (JOptionPane.showConfirmDialog(null, "Είστε σίγουρος ότι θέλετε να διαγράψετε το επιλεγμένο Συγκρότημα;", "Διαγραφή", JOptionPane.YES_NO_OPTION)==JOptionPane.YES_OPTION){
              if (!em.getTransaction().isActive()){
            em.getTransaction().begin();
        }
                try{
                    Musicgroup mdel= em.createNamedQuery("Musicgroup.findByMusicGroupId", Musicgroup.class).setParameter("musicGroupId", m.getMusicGroupId()).getSingleResult();            
                    List listTodel= em.createNamedQuery("Album.findByFkGroup", Album.class).setParameter("fkMusicgroupid", mdel).getResultList();
                    if (!listTodel.isEmpty()) { // σβήνω τα αλμπουμ των γκρουπ
                        Iterator itr=listTodel.iterator();
                        while (itr.hasNext()){
                            Album al = (Album)itr.next();
                            em.remove(al);
                                }
                     }
                    em.remove(mdel);
                    em.getTransaction().commit();
                    musicgroupList.remove(s);
                    GroupTable.repaint();
                } catch (Exception e) {
                    e.printStackTrace();
                    em.getTransaction().rollback();
                }
            }
        }
        else{
            JOptionPane.showMessageDialog(null, "Δεν επιλέξατε κάποιο συγκρότημα", "Σφάλμα", JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_delGroupActionPerformed

    private void GroupTableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_GroupTableMouseClicked
        // TODO add your handling code here:
          checkButtons();
    }//GEN-LAST:event_GroupTableMouseClicked

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(ListMusicGroupForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(ListMusicGroupForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(ListMusicGroupForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ListMusicGroupForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
        //</editor-fold>
        //</editor-fold>
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new ListMusicGroupForm().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTable GroupTable;
    private javax.persistence.EntityManager RadiostationPUEntityManager;
    private javax.swing.JButton delGroup;
    private javax.swing.JButton editGroup;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton4;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    private java.util.List<radiostation_POJOS.Musicgroup> musicgroupList;
    private javax.persistence.Query musicgroupQuery;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables
}
